package com.gigmissions.server.services.servlets;

import java.io.IOException;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;



public class FileUploadServlet extends javax.servlet.http.HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 6545841963944756375L;

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		super.doGet(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
		
		response.setContentType("text/html;charset=UTF-8");
		 
		//verify that the request is multipart
		boolean isMultipart = ServletFileUpload.isMultipartContent(request);
		 
		FileItemFactory factory = new DiskFileItemFactory();
		 
		ServletFileUpload upload = new ServletFileUpload(factory);
		try {
		     //get the items from the request object
		     List items = upload.parseRequest(request);
		 
		     Iterator iter = items.iterator();
		     while(iter.hasNext()){
		           Object obj = iter.next();
		           //make sure the object is not null
		           if(obj == null){
		                continue;
		           }
		 
		            FileItem item = (FileItem)obj;
		 
		           //if item is a form field then get the value from the item
		          if(item.isFormField()){
		              String name = item.getName();
		              if(name.compareTo("textBoxFormElement")==0){
		                   //do something with the text box value
		                   String value = item.getString();
		              }else{
		                   //do something with the list box value
		                   String value = item.getString();
		              }
		          //if the item is not a form field, you know you have
		         //an uploaded file, and therefore you need to process
		         //it as such.
		        }else if(!item.isFormField()){
		 
		                //Here we can do whatever we want with the uploaded file.
		               String name = item.getName();
		        }
		  }
		 
		     response.getWriter().write("Success in processing multipart MIME form");
		} catch (Exception ex) {
		}
	}
	
	
	

}
